package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.annotation.AuditLogAnnotation;
import com.micro.ai.auth.entity.AuditLog;
import com.micro.ai.auth.service.AuditLogService;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 审计日志控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/audit-logs")
@Tag(name = "审计日志管理", description = "操作审计日志的查询和管理")
public class AuditLogController {

    @Autowired
    private AuditLogService auditLogService;

    /**
     * 分页查询审计日志
     */
    @GetMapping
    @Operation(summary = "分页查询审计日志", description = "根据条件分页查询操作审计日志")
    @AuditLogAnnotation(action = "VIEW", resourceType = "AUDIT_LOG", description = "查询审计日志")
    public ApiResponse<IPage<AuditLog>> getAuditLogPage(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "操作动作") @RequestParam(required = false) String action,
            @Parameter(description = "资源类型") @RequestParam(required = false) String resourceType,
            @Parameter(description = "开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        Page<AuditLog> page = new Page<>(pageNum, pageSize);
        IPage<AuditLog> result = auditLogService.getAuditLogPage(page, userId, tenantId, action, resourceType, startTime, endTime);
        
        return ApiResponse.success(result);
    }

    /**
     * 获取审计日志详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取审计日志详情", description = "根据ID获取审计日志的详细信息")
    @AuditLogAnnotation(action = "VIEW", resourceType = "AUDIT_LOG", description = "查看审计日志详情")
    public ApiResponse<AuditLog> getAuditLogById(
            @Parameter(description = "审计日志ID") @PathVariable String id) {
        
        AuditLog auditLog = auditLogService.getById(id);
        if (auditLog == null) {
            return ApiResponse.error("审计日志不存在", "AUDIT_LOG_NOT_FOUND");
        }
        
        return ApiResponse.success(auditLog);
    }

    /**
     * 查询用户的最近操作日志
     */
    @GetMapping("/user/{userId}/recent")
    @Operation(summary = "查询用户最近操作", description = "查询指定用户的最近操作日志")
    @AuditLogAnnotation(action = "VIEW", resourceType = "AUDIT_LOG", description = "查询用户最近操作")
    public ApiResponse<List<AuditLog>> getRecentLogsByUserId(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "限制数量", example = "10") @RequestParam(defaultValue = "10") Integer limit) {
        
        List<AuditLog> logs = auditLogService.getRecentLogsByUserId(userId, limit);
        return ApiResponse.success(logs);
    }

    /**
     * 查询资源的操作历史
     */
    @GetMapping("/resource/{resourceType}/{resourceId}")
    @Operation(summary = "查询资源操作历史", description = "查询指定资源的所有操作历史")
    @AuditLogAnnotation(action = "VIEW", resourceType = "AUDIT_LOG", description = "查询资源操作历史")
    public ApiResponse<List<AuditLog>> getLogsByResource(
            @Parameter(description = "资源类型") @PathVariable String resourceType,
            @Parameter(description = "资源ID") @PathVariable String resourceId) {
        
        List<AuditLog> logs = auditLogService.getLogsByResource(resourceType, resourceId);
        return ApiResponse.success(logs);
    }

    /**
     * 获取操作统计
     */
    @GetMapping("/stats")
    @Operation(summary = "获取操作统计", description = "获取操作统计信息")
    @AuditLogAnnotation(action = "VIEW", resourceType = "AUDIT_LOG", description = "查询操作统计")
    public ApiResponse<List<AuditLog>> getOperationStats(
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        List<AuditLog> stats = auditLogService.getOperationStats(userId, tenantId, startTime, endTime);
        return ApiResponse.success(stats);
    }

    /**
     * 清理过期审计日志
     */
    @DeleteMapping("/clean")
    @Operation(summary = "清理过期审计日志", description = "清理指定天数前的审计日志")
    @AuditLogAnnotation(action = "DELETE", resourceType = "AUDIT_LOG", description = "清理过期审计日志")
    public ApiResponse<Integer> cleanExpiredLogs(
            @Parameter(description = "保留天数", example = "90") @RequestParam(defaultValue = "90") int days) {
        
        int count = auditLogService.cleanExpiredLogs(days);
        return ApiResponse.success(count, "清理完成，共清理 " + count + " 条记录");
    }
}
